//
//  FPAuthenFaceWebViewController.m
//  FinanceProject
//
//  Created by 王建龙 on 2025/6/26.
//

#import "FPAuthenFaceWebViewController.h"
#import <CommonCrypto/CommonCrypto.h>
#import <WebKit/WebKit.h>

@interface FPAuthenFaceWebViewController ()<WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, assign) BOOL hasHandledCameraDenial; // 添加实例变量

@end

@implementation FPAuthenFaceWebViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self removeWebViewObserver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 确保人脸识别页面不显示TabBar
    self.hidesBottomBarWhenPushed = YES;
    
    [self setTitle:@"实名认证" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    self.view.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    // 初始化状态变量
    self.hasHandledCameraDenial = NO;
    
    [self setupWebView];
    // Do any additional setup after loading the view.
}
- (void)setupWebView {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
    if (@available(iOS 15.0, *)) {
        config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
    }
    
    // 添加消息处理器来接收JavaScript消息
    [config.userContentController addScriptMessageHandler:self name:@"pageInteraction"];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0., UIDevice.navigationFullHeight-UIDevice.navigationHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight+UIDevice.navigationHeight) configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    // 添加加载进度监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.view addSubview:self.webView];
    
    [self loadWebViewWithUrl];
    [self.view bringSubviewToFront:self.navView];
}
#pragma mark - 加载页面
- (void)loadWebViewWithUrl{
    NSURL *url = [NSURL URLWithString:self.faceUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
- (void)backAction {
    if (self.webView && [self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self detainmentPopupAction];
    }
}
- (void)detainmentPopupAction {
    
    LXAlertView *alert = [[LXAlertView alloc] initDetainmentWithTitleString:@"确认退出吗" contentString:@"额度最高20万元，最快3分钟即可放款" btn1:@"去意已决" btn2:@"我再想想" alertAlertResult:^(NSInteger index) {
        
        if (index == 2) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [alert showLXAlertView];
}
#pragma mark - 拦截跳转，识别完成回调
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    NSString *requestURL = navigationAction.request.URL.absoluteString;
    NSLog(@"页面跳转URL: %@", requestURL);
//    if ([requestURL containsString:@"auth/face/redirect"]) {
//        // 人脸识别完成
//        NSString *result = [self getQueryParam:@"result" fromURL:requestURL];
//        NSString *code = [self getQueryParam:@"code" fromURL:requestURL];
//        NSLog(@"识别状态，result: %@", result);
//        if ([result isEqualToString:@"false"] || ([code integerValue] != 100000 && [code integerValue] != 0)) {
//            [self removeWebViewObserver];
//            [self showText:@"人脸识别失败，请重试"];
//            [self.navigationController popViewControllerAnimated:YES];
//            decisionHandler(WKNavigationActionPolicyCancel);
//            return;
//        }
//    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WebView加载完成代理方法
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [MBManager hideLoading];
    
    // 获取当前页面的URL
    NSString *currentURL = webView.URL.absoluteString;
    NSLog(@"页面加载完成URL: %@", currentURL);
    
    // 监听页面加载完成的URL
    [self handleURLChange:currentURL withType:@"页面加载完成"];
    
    // 注入JavaScript监听页面交互事件
    [self injectJavaScriptForEventListening:webView];
    
    // 更新导航栏返回按钮状态
    [self updateNavigationBarForWebView];
    
    // 打印当前WebView的返回状态
    NSLog(@"WebView加载完成，canGoBack: %@", self.webView.canGoBack ? @"YES" : @"NO");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *js = @"var nav = document.querySelector('.nav-bar'); if(nav){nav.style.display='none';}";
        [webView evaluateJavaScript:js completionHandler:nil];
    });
}

#pragma mark - KVO监听WebView加载进度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        float progress = [change[NSKeyValueChangeNewKey] floatValue];
        NSLog(@"WebView加载进度: %.2f%%", progress * 100);
        if (progress >= 0.9) {
            [MBManager hideLoading];
        }
    }
}

#pragma mark - 页面销毁时移除KVO监听
- (void)dealloc {
    [self removeWebViewObserver];
    [self removeScriptMessageHandler];
}

#pragma mark - 移除WebView的KVO监听
- (void)removeWebViewObserver {
    if (self.webView) {
        @try {
            [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        } @catch (NSException *exception) {
            NSLog(@"移除KVO监听异常: %@", exception.reason);
        }
    }
}

#pragma mark - 移除JavaScript消息处理器
- (void)removeScriptMessageHandler {
    if (self.webView) {
        @try {
            [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"pageInteraction"];
        } @catch (NSException *exception) {
            NSLog(@"移除消息处理器异常: %@", exception.reason);
        }
    }
}

#pragma mark - 重试人脸识别请求
- (void)retryFaceAuthRequest {
    // 重新调用人脸识别请求
//    [self openFaceAuthFirst];
}

#pragma mark - WKUIDelegate（支持 JS alert）
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message
initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 提示弹窗
- (void)showAlertWithMessage:(NSString *)msg {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:msg
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"我知道了"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 解析 URL 参数
- (NSString *)getQueryParam:(NSString *)key fromURL:(NSString *)urlString {
    NSRange range = [urlString rangeOfString:@"?"];
    if (range.location == NSNotFound) return nil;
    
    NSString *query = [urlString substringFromIndex:range.location + 1];
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        if (kv.count == 2 && [kv[0] isEqualToString:key]) {
            return kv[1];
        }
    }
    return nil;
}


#pragma mark - 更新导航栏状态
- (void)updateNavigationBarForWebView {
    if (self.webView) {
        // 如果WebView可以返回，显示WebView的返回逻辑
        if (self.webView.canGoBack) {
            // 可以添加一个自定义的返回按钮，或者保持当前逻辑
            NSLog(@"WebView可以返回上一页");
        } else {
            // WebView无法返回，显示退出确认逻辑
            NSLog(@"WebView无法返回，显示退出确认");
        }
    }
}

#pragma mark - WebView导航状态变化监听
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    // WebView开始加载新页面时调用
    NSString *currentURL = webView.URL.absoluteString;
    NSLog(@"页面开始加载URL: %@", currentURL);
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    // WebView收到服务器重定向时调用
    NSString *currentURL = webView.URL.absoluteString;
    NSLog(@"页面重定向URL: %@", currentURL);
}

#pragma mark - 处理URL变化
- (void)handleURLChange:(NSString *)url withType:(NSString *)type {
    if (!url || url.length == 0) {
        return;
    }
    NSString *authResult = [self getQueryParam:@"result" fromURL:url];
    NSLog(@"=== URL变化监听 ===");
    NSLog(@"类型: %@", type);
    NSLog(@"URL: %@", url);
    NSLog(@"时间: %@", [NSDate date]);
    NSLog(@"authResult: %@", authResult);
    NSLog(@"==================");
    if ([authResult intValue] == 1) {
        [MBManager hideLoading];
        NSMutableDictionary *param = [NSMutableDictionary new];
        param[@"serialNo"] = self.serialNo;
        [FPUserModel realNameAuthResultWithParam:param success:^(NSString * _Nonnull message, NSInteger code, NSInteger result) {
            if (code == 200) {
                [MBManager hideLoading];
                if (result == 1) {
                    [self.navigationController popViewControllerAnimated:YES];
                    // 比对通过
                    if (self.authSuccessBlock) {
                        self.authSuccessBlock();
                    }
                } else {
                    [self showText:@"人脸比对不通过，请重试"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else{
                [MBManager hideLoading];
                [self showText:message];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(NSError * _Nonnull error) {
            [MBManager hideLoading];
            [self showError:error];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else if ([authResult intValue] == -1) {
        [self showText:@"人脸识别失败，请重试"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 注入JavaScript监听页面交互事件
- (void)injectJavaScriptForEventListening:(WKWebView *)webView {
    // 注入点击事件监听器
    [self injectClickListener:webView];
    
    // 延迟注入摄像头权限监听
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self injectCameraPermissionListeners:webView];
    });
}

#pragma mark - 注入点击监听器
- (void)injectClickListener:(WKWebView *)webView {
    NSString *clickJsCode = @"document.addEventListener('click', function(event) { \
        var target = event.target; \
        if (target && target.tagName) { \
            var eventInfo = { \
                type: 'click', \
                tagName: target.tagName.toLowerCase(), \
                text: (target.textContent || target.innerText || '').substring(0, 50), \
                timestamp: new Date().toISOString() \
            }; \
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pageInteraction) { \
                window.webkit.messageHandlers.pageInteraction.postMessage(eventInfo); \
            } \
        } \
    }, true);";
    
    [webView evaluateJavaScript:clickJsCode completionHandler:nil];
}

#pragma mark - 注入摄像头权限监听器
- (void)injectCameraPermissionListeners:(WKWebView *)webView {
    NSString *cameraJsCode = @"if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { \
        var originalGetUserMedia = navigator.mediaDevices.getUserMedia; \
        var hasSentDenialMessage = false; \
        navigator.mediaDevices.getUserMedia = function(constraints) { \
            var eventInfo = { \
                type: 'camera_permission_request', \
                constraints: JSON.stringify(constraints), \
                timestamp: new Date().toISOString() \
            }; \
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pageInteraction) { \
                window.webkit.messageHandlers.pageInteraction.postMessage(eventInfo); \
            } \
            return originalGetUserMedia.call(this, constraints).then(function(stream) { \
                var successInfo = { \
                    type: 'camera_permission_granted', \
                    timestamp: new Date().toISOString() \
                }; \
                if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pageInteraction) { \
                    window.webkit.messageHandlers.pageInteraction.postMessage(successInfo); \
                } \
                return stream; \
            }).catch(function(error) { \
                if (!hasSentDenialMessage) { \
                    hasSentDenialMessage = true; \
                    var errorInfo = { \
                        type: 'camera_permission_denied', \
                        error: (error.name || 'Unknown') + ': ' + (error.message || 'Unknown error'), \
                        timestamp: new Date().toISOString() \
                    }; \
                    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pageInteraction) { \
                        window.webkit.messageHandlers.pageInteraction.postMessage(errorInfo); \
                    } \
                } \
                throw error; \
            }); \
        }; \
    }";
    
    [webView evaluateJavaScript:cameraJsCode completionHandler:nil];
}

#pragma mark - WKScriptMessageHandler - 接收JavaScript消息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"pageInteraction"]) {
        [self handlePageInteraction:message.body];
    }
}

#pragma mark - 处理页面交互事件
- (void)handlePageInteraction:(id)messageBody {
    if (![messageBody isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSDictionary *eventInfo = (NSDictionary *)messageBody;
    NSString *eventType = eventInfo[@"type"];
    
    // 根据事件类型处理不同的交互
    if ([eventType isEqualToString:@"click"]) {
        [self handleClickEvent:eventInfo];
    } else if ([eventType isEqualToString:@"alert"]) {
        [self handleAlertEvent:eventInfo];
    } else if ([eventType isEqualToString:@"confirm"]) {
        [self handleConfirmEvent:eventInfo];
    } else if ([eventType isEqualToString:@"prompt"]) {
        [self handlePromptEvent:eventInfo];
    } else if ([eventType isEqualToString:@"form_submit"]) {
        [self handleFormSubmitEvent:eventInfo];
    } else if ([eventType isEqualToString:@"input_change"]) {
        [self handleInputChangeEvent:eventInfo];
    } else if ([eventType isEqualToString:@"camera_permission_request"] || 
               [eventType isEqualToString:@"camera_permission_request_old"]) {
        [self handleCameraPermissionRequest:eventInfo];
    } else if ([eventType isEqualToString:@"camera_permission_granted"] || 
               [eventType isEqualToString:@"camera_permission_granted_old"]) {
        [self handleCameraPermissionGranted:eventInfo];
    } else if ([eventType isEqualToString:@"camera_permission_denied"] || 
               [eventType isEqualToString:@"camera_permission_denied_old"]) {
        [self handleCameraPermissionDenied:eventInfo];
    } else if ([eventType isEqualToString:@"js_error"]) {
        [self handleJavaScriptError:eventInfo];
    }
}

#pragma mark - 处理点击事件
- (void)handleClickEvent:(NSDictionary *)eventInfo {
    NSString *tagName = eventInfo[@"tagName"];
    NSString *className = eventInfo[@"className"];
    NSString *id = eventInfo[@"id"];
    NSString *text = eventInfo[@"text"];
    NSString *href = eventInfo[@"href"];
    
    // 根据点击的元素执行相应操作
    if ([tagName isEqualToString:@"button"]) {
        // 按钮点击处理
    } else if ([tagName isEqualToString:@"a"]) {
        // 链接点击处理
    } else if ([tagName isEqualToString:@"input"]) {
        // 输入框点击处理
    }
}

#pragma mark - 处理弹窗事件
- (void)handleAlertEvent:(NSDictionary *)eventInfo {
    NSString *message = eventInfo[@"message"];
    // alert弹窗处理
}

- (void)handleConfirmEvent:(NSDictionary *)eventInfo {
    NSString *message = eventInfo[@"message"];
    // confirm弹窗处理
}

- (void)handlePromptEvent:(NSDictionary *)eventInfo {
    NSString *message = eventInfo[@"message"];
    NSString *defaultValue = eventInfo[@"defaultValue"];
    // prompt弹窗处理
}

#pragma mark - 处理表单提交事件
- (void)handleFormSubmitEvent:(NSDictionary *)eventInfo {
    NSString *formId = eventInfo[@"formId"];
    NSString *formAction = eventInfo[@"formAction"];
    NSString *formMethod = eventInfo[@"formMethod"];
    // 表单提交处理
}

#pragma mark - 处理输入框变化事件
- (void)handleInputChangeEvent:(NSDictionary *)eventInfo {
    NSString *inputType = eventInfo[@"inputType"];
    NSString *inputName = eventInfo[@"inputName"];
    NSString *inputId = eventInfo[@"inputId"];
    NSString *value = eventInfo[@"value"];
    // 输入框变化处理
}

#pragma mark - 处理摄像头权限请求
- (void)handleCameraPermissionRequest:(NSDictionary *)eventInfo {
    // 摄像头权限请求处理
}

#pragma mark - 处理摄像头权限已授予
- (void)handleCameraPermissionGranted:(NSDictionary *)eventInfo {
    // 摄像头权限已授予处理
}

#pragma mark - 处理摄像头权限已拒绝
- (void)handleCameraPermissionDenied:(NSDictionary *)eventInfo {
    if (self.hasHandledCameraDenial) {
        return;
    }
    
    NSString *error = eventInfo[@"error"];
    
    // 用户拒绝了摄像头权限
    if ([error containsString:@"NotAllowedError"] || 
        [error containsString:@"PermissionDeniedError"] ||
        [error containsString:@"NotAllowed"]) {
        
        self.hasHandledCameraDenial = YES;
        
        [self showText:@"摄像头权限被拒绝，无法进行人脸识别"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 处理JavaScript错误
- (void)handleJavaScriptError:(NSDictionary *)eventInfo {
    // JavaScript错误处理
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
